﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
/// <summary>
/// Summary description for XuLyGioHang
/// </summary>
public class XuLyGioHang
{
    public DataTable dssp;

	public XuLyGioHang()
	{
        dssp = new DataTable();
        dssp.Columns.Add("MaSP");
        dssp.Columns.Add("TenSP");
        dssp.Columns.Add("Gia");
        dssp.Columns.Add("SoLuong");
        dssp.Columns.Add("Thanhtien");
	}

    public void ThemSanPham(int MaSP)
    {
        string sql = "select TenSP, Gia from SanPham Where MaSP=" + MaSP;
        DataTable thongtinsp = Xulydulieu.ExecuteQuery(sql);
        string tensp = thongtinsp.Rows[0].ItemArray[0].ToString();
        int dongia = Convert.ToInt32(thongtinsp.Rows[0].ItemArray[1]);

        int dong = KiemTra(MaSP);
        if (dong == -1)
        {
            dssp.Rows.Add(MaSP, tensp, dongia, 1, dongia);
        }
        else
        {
            int soluong = Convert.ToInt32(dssp.Rows[dong].ItemArray[3]) + 1;
            dssp.Rows.RemoveAt(dong);
            dssp.Rows.Add(MaSP, tensp, dongia, soluong, soluong * dongia);
        }
    }

    public int KiemTra(int MaSP)
    {
        for (int i = 0; i < dssp.Rows.Count; i++)
        {
            if (Convert.ToInt32(dssp.Rows[i].ItemArray[0]) == MaSP)
                return i;
        }
        return -1;
    }

    public void XoaSanPham(int MaSP)
    {
        int dong = KiemTra(MaSP);
        if (dong != -1)
        {
            dssp.Rows.RemoveAt(dong);
        }
    }

    public void CapNhatSoLuong(int MaSP, int soluongmoi)
    {
        int dong = KiemTra(MaSP);
        if (dong != -1)
        {
            string tensp = dssp.Rows[dong].ItemArray[1].ToString();
            int dongia = Convert.ToInt32(dssp.Rows[dong].ItemArray[2]) ;

            dssp.Rows.RemoveAt(dong);

            dssp.Rows.Add(MaSP, tensp, dongia, soluongmoi, soluongmoi * dongia);
        }
    }

    public void XoaTatCa()
    {
        dssp.Rows.Clear();
    }
   
    public int TinhTongTien()
    {
        int sum = 0;
        for (int i = 0; i < dssp.Rows.Count; i++)
        {
            sum += Convert.ToInt32(dssp.Rows[i].ItemArray[4]);
        }
        return sum;
    }
}